<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { resetForm, objCoppy, myConfrim } from '@/utils'
import { getBuildListApi, getStoryListApi } from '@/api/build'
import { addApi, getRoomListApi, editApi, deleteApi, initBedApi, deleteBedApi, editBedApi } from '@/api/setCode'


// 楼栋id
const storeyId = ref('')
// 楼栋列表
const buildList = ref([])
// 层数列表
const storyList = ref([])
// 楼栋点击颜色切换
const isChange = ref(0)
// 层数点击颜色切换
const isDestory = ref(0)
const leftHeight = ref(0)
const rightHeight = ref(0)
// 弹框属性
const addDialog = reactive({
    visible: false,
    title: '',
    width: 600,
    height: 250
})
// 表单绑定对象
const addModel = reactive({
    area: '',
    start: '',
    end: '',
    stuNum: '',
    storeyId: '',
    roomType: ''
})
// 编辑弹框属性
const editDialog = reactive({
    visible: false,
    title: '',
    width: 600,
    height: 180
})
// 编辑表单绑定对象
const editModel = reactive({
    roomId: '',
    storeyId: '',
    roomType: '',
    roomCode: '',
    totalBed: ''
})
// 编辑宿舍弹窗
const childDialog = reactive({
    visible: false,
    title: '',
    width: 600,
    height: 180
})
// 编辑床位绑定对象
const childModel = reactive({
    bedId: '',
    roomId: '',
    bedCode: ''
})
// 表单校验规则
const rules = {
    area: [
        { required: true, message: '请输入区域', trigger: 'blur' }
    ],
    start: [
        { required: true, message: '请输入开始编号', trigger: 'blur' }
    ],
    end: [
        { required: true, message: '请输入结束编号', trigger: 'blur' }
    ],
    roomType: [
        { required: true, message: '请输入房间类型', trigger: 'blur' }
    ],
    stuNum: [
        { required: true, message: '请输入人数', trigger: 'blur' }
    ],
}
// 编辑表单校验规则
const editRules = {
    roomType: [
        {
            required: true,
            message: '请选择房间类型',
            trigger: 'blur'
        }
    ],
    roomCode: [
        {
            required: true,
            message: '请输入宿舍编号',
            trigger: 'blur'
        }
    ],
    totalBed: [
        {
            required: true,
            message: '请输入容纳人数',
            trigger: 'blur'
        }
    ]
}
// 编辑宿舍表单校验规则
const childRules = {
    bedCode: [
        { required: true, message: '请输入床位编号', trigger: 'blur' }
    ]
}
// 房间类型
const roomTypes = [
    {
        value: '1',
        label: '1人间'
    },
    {
        value: '2',
        label: '2人间'
    },
    {
        value: '4',
        label: '4人间'
    },
    {
        value: '6',
        label: '6人间'
    },
    {
        value: '8',
        label: '8人间'
    },
]
// 分页查询对象
const listParm = reactive({
    storeyId: '',
    currentPage: 1,
    pageSize: 10,
    total: 0
})
// 表格高度
const tableHeight = ref(0)
// 表格数据
const tableData = ref([])


onMounted(() => {
    leftHeight.value = window.innerHeight - 230
    rightHeight.value = window.innerHeight - 230
    tableHeight.value = window.innerHeight - 330
})

// 获取表格数据
const getList = async () => {
    let res = await getRoomListApi(listParm)
    if (res) {
        tableData.value = res.data.records
        listParm.total = res.data.total
    }
}
// 获取楼栋列表
const getBuildList = async () => {
    let res = await getBuildListApi()
    if (res) {
        buildList.value = res.data
        // 点击到第一个楼栋
        nextTick(() => {
            document.querySelector('#build0').click()
        })
    }
}

getBuildList()

// 获取层数列表
const getStoryList = async (buildId) => {
    let res = await getStoryListApi({
        buildId
    })
    if (res) {
        storyList.value = res.data
        nextTick(() => {
            document.querySelector('#storey0').click()
        })
    }
}
// 楼栋点击事件
const btnClick = async (buildId, index) => {
    isChange.value = index
    isDestory.value = 0
    getStoryList(buildId)
    console.log('楼栋点击', buildId)
}
// 层数点击事件
const storyClick = (storyId, index) => {
    isDestory.value = index
    storeyId.value = storyId
    listParm.storeyId = storyId
    // 获取对应的表格数据
    getList()
}
const addForm = ref(null)
// 添加按钮
const addBtn = () => {
    // 清空上一次的数据
    resetForm(addForm.value, addModel)
    addDialog.title = '设置编号'
    // 楼栋id
    addModel.storeyId = storeyId.value
    addDialog.visible = true
}
// 弹窗确认
const onConfirm = async () => {
    await addForm.value.validate(async vaild => {
        if (vaild) {
            let res = await addApi(addModel)
            if (res) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
                getList()
                addDialog.visible = false
            }
        }
    })
}
// 弹窗取消
const onClose = () => addDialog.visible = false
// 房间类型选择事件
const selectChange = (val) => addModel.stuNum = val

const sizeChange = (size) => {
    listParm.pageSize = size
    listParm.currentPage = 1
    getList()
}

const currentChange = (page) => {
    listParm.currentPage = page
    getList()
}
const editForm = ref(null)
// 编辑房间
const editBtn = (row) => {
    // 清空上一次的数据
    resetForm(editForm.value, editModel)
    editDialog.title = '编辑房间'
    // 把要编辑的数据赋值给表单
    objCoppy(row, editModel)
    editDialog.visible = true
}
// 删除房间
const deleteBtn = async (row) => {
    const confirm = await myConfrim('确定要删除该房间吗?')
    if (confirm) {
        let res = await deleteApi({
            roomId: row.roomId
        })
        if (res) {
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            getList()
        }
    }
}
// 编辑弹窗确认事件
const onEditConfirm = async () => {
    await editForm.value.validate(async valid => {
        if (valid) {
            const res = await editApi(editModel)
            if (res) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
                getList()
                editDialog.visible = false
            }
        }
    })
}
// 编辑弹窗取消事件
const onEditClose = () => editDialog.visible = false
// 编辑房间类型选择事件
const editSelectChange = (val) => editModel.totalBed = val

// 初始化床位
const initBed = async () => {
    if (!storeyId.value) {
        ElMessage({
            message: '请先选择层数',
            type: 'error',
        })
        return
    }
    let res = await initBedApi({
        storeyId: storeyId.value
    })
    if (res) {
        ElMessage({
            message: res.msg,
            type: 'success',
        })
        getList()
    }
}
// 床位编辑
const childEdit = (row) => {
    // 把要编辑的数据赋值给表单
    objCoppy(row, childModel)
    childDialog.title = '编辑床位'
    childDialog.visible = true
}
// 床位删除
const childDelete = async (row) => {
    let confirm = await myConfrim('确定要删除该床位吗?')
    if (confirm) {
        let res = await deleteBedApi({
            bedId: row.bedId
        })
        if (res) {
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            getList()
        }
    }
}
const childForm = ref(null)
// 床位编辑弹窗确认事件
const onChildConfirm = async () => {
    await childForm.value.validate(async valid => {
        if (valid) {
            let res = await editBedApi(childModel)
            if (res) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
                getList()
                childDialog.visible = false
            }
        }
    })
}
// 床位编辑弹窗取消事件
const onChildClose = () => childDialog.visible = false
</script>

<template>
    <!-- 楼栋布局 -->
    <el-divider content-position="left">楼宇</el-divider>
    <div class="build-list">
        <div class="build-item" :id="'build' + index" @click="btnClick(item.buildId, index)"
            v-for="(item, index) in buildList" :key="index" :class="{ isActive: isChange === index }">
            {{ item.buildName }}
        </div>
    </div>

    <el-container class="containers">
        <el-aside :style="{ height: leftHeight + 'px' }" class="leftAsside" width="180px">
            <div @click="storyClick(item.storeyId, index)" :class="{ destoryActive: isDestory === index }"
                :id="'storey' + index" class="story-item" v-for="(item, index) in storyList" :key="index">
                {{ item.storeyName }}
            </div>
        </el-aside>
        <el-main class="mains">
            <div mb-2>
                <el-button icon="Plus" type="primary" @click="addBtn">新增</el-button>
                <el-button icon="Plus" type="primary" @click="initBed">初始化床位</el-button>
            </div>
            <!-- 表格 -->
            <el-table :height="tableHeight" :data="tableData" border stripe>
                <el-table-column width="100" type="expand">
                    <template #default="scope">
                        <el-table border :data="scope.row.bedList">
                            <el-table-column label="床位编号" prop="bedCode"></el-table-column>
                            <el-table-column fixed="right" label="操作" align="center" width="200">
                                <template #default="scopeSub">
                                    <div flex>
                                        <el-button round type="success" icon="Edit"
                                            @click="childEdit(scopeSub.row)">编辑</el-button>
                                        <el-button round type="danger" icon="Delete"
                                            @click="childDelete(scopeSub.row)">删除</el-button>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column label="宿舍编号" prop="roomCode"></el-table-column>
                <el-table-column align="center" label="宿舍类型">
                    <template #default="scope">
                        <el-tag v-if="scope.row.roomType === '1'">1人间</el-tag>
                        <el-tag v-if="scope.row.roomType === '2'">2人间</el-tag>
                        <el-tag v-if="scope.row.roomType === '4'">4人间</el-tag>
                        <el-tag v-if="scope.row.roomType === '6'">6人间</el-tag>
                        <el-tag v-if="scope.row.roomType === '8'">8人间</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="totalBed" label="人数"></el-table-column>
                <el-table-column fixed="right" align="center" label="操作" width="200">
                    <template #default="scope">
                        <el-button icon="Edit" type="primary" @click="editBtn(scope.row)">编辑</el-button>
                        <el-button icon="Delete" type="danger" @click="deleteBtn(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination @size-change="sizeChange" @current-change="currentChange"
                :current-page.sync="listParm.currentPage" :page-sizes="[10, 20, 40, 80, 100]" :page-size="listParm.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="listParm.total">
            </el-pagination>
        </el-main>
    </el-container>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addDialog.visible" :width="addDialog.width" :close-on-click-modal="false">
        <template #header>
            <h1>{{ addDialog.title }}</h1>
        </template>
        <div :style="{ height: addDialog.height + 'px' }">
            <el-form :model="addModel" ref="addForm" :rules="rules" label-width="80px">
                <el-form-item prop="area" label="区域">
                    <el-input v-model="addModel.area"></el-input>
                </el-form-item>
                <el-row>
                    <el-col :span="12" :offset="0">
                        <el-form-item prop="start" label="开始编号">
                            <el-input v-model="addModel.start"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item prop="end" label="结束编号">
                            <el-input v-model="addModel.end"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item prop="roomType" label="类型">
                    <el-select style="width: 42%;" @change="selectChange" v-model="addModel.roomType" placeholder="请选择房间类型">
                        <el-option v-for="(item, index) in roomTypes" :label="item.label" :value="item.value"
                            :key="index"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="stuNum" label="人数">
                    <el-input v-model="addModel.stuNum"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="onClose">取消</el-button>
                <el-button type="primary" @click="onConfirm">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 编辑宿舍弹窗 -->
    <el-dialog v-model="editDialog.visible" :width="editDialog.width" :close-on-click-modal="false">
        <template #header>
            <h1>{{ editDialog.title }}</h1>
        </template>
        <div :style="{ height: editDialog.height + 'px' }">
            <el-form :model="editModel" ref="editForm" :rules="editRules" label-width="80px">
                <el-form-item prop="roomCode" label="宿舍编号">
                    <el-input v-model="editModel.roomCode" placeholder="请输入名称"></el-input>
                </el-form-item>
                <el-form-item prop="roomType" label="类型">
                    <el-select style="width: 100%;" @change="editSelectChange" v-model="editModel.roomType"
                        placeholder="请选择房间类型">
                        <el-option v-for="(item, index) in roomTypes" :label="item.label" :value="item.value"
                            :key="index"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="totalBed" label="容纳人数">
                    <el-input v-model="editModel.totalBed" placeholder="请输入容纳人数"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="onEditClose">取消</el-button>
                <el-button type="primary" @click="onEditConfirm">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 编辑床位弹窗 -->
    <el-dialog v-model="childDialog.visible" :width="childDialog.width" :close-on-click-modal="false">
        <template #header>
            <h1>{{ childDialog.title }}</h1>
        </template>
        <div :style="{ height: childDialog.height + 'px' }">
            <el-form :model="childModel" ref="childForm" :rules="childRules" label-width="80px">
                <el-form-item prop="bedCode" label="床位编号">
                    <el-input v-model="childModel.bedCode" placeholder="请输入床位编号"></el-input>
                </el-form-item>

            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="onChildClose">取消</el-button>
                <el-button type="primary" @click="onChildConfirm">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped>
.build-list {
    display: flex;
    flex-wrap: wrap;
}

.build-item {
    padding: 4px 20px;
    margin: 8px;
    font-size: 14px;
    border: 1px solid #dedede;
    border-radius: 4px;
    cursor: pointer;
    background: #f8f8f8;
}

.isActive {
    background: #42b983;
    color: #fff;
}

.containers {
    margin-top: 20px;
    border: 1px solid #dcdfe6;
}

.leftAsside {
    border-right: 1px solid #dcdfe6;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.story-item {
    padding: 4px 30px;
    margin: 10px;
    font-size: 14px;
    border: 1px solid #dedede;
    border-radius: 4px;
    cursor: pointer;
    background-color: #f8f8f8;
}

.destoryActive {
    background: #5fb878;
    border-color: #5fb878;
    color: #fff;
}

.mains {
    padding-top: 10px;
}
</style>